﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Projektet.Model.Combat
{
    class CombatHandler
    {
        public void CheckForContact(List<CombatUnit> attackerList, List<CombatUnit> defenderList)
        {
            foreach(CombatUnit aUnit in attackerList)
            {
                if(defenderList.Count == 0)
                {
                    aUnit._unitState = UnitState.Moving;
                }
                List<CombatUnit> inContactList = new List<CombatUnit>();
                
                foreach (CombatUnit dUnit in defenderList)
                {
                    if(aUnit.IsInContact(dUnit._unitRect))
                    {
                        inContactList.Add(dUnit);
                    }
                }

                //Makes sure the castle is the last unit attacked if others are available
                
                //foreach(CombatUnit tUnit in inContactList)
                //{
                //    if(tUnit.GetType().Name == "Castle" && inContactList.Count >= 2)
                //    {
                //        inContactList.Remove(tUnit);
                //    }
                //}
                for (int i = inContactList.Count; i > 0; i--)
                {
                    if (inContactList[i - 1].GetType().Name == "Castle" && inContactList.Count >= 2)
                    {
                        inContactList.RemoveAt(i - 1);
                    }
                }

                if (inContactList.Count > 0)
                {
                    ResolveCombat(aUnit, inContactList[0]);
                }
                else
                {
                    aUnit._unitState = UnitState.Moving;
                }
            }
            for (int i = defenderList.Count; i > 0; i--)
            {
                if(defenderList[i - 1].IsDead())
                {
                    defenderList.RemoveAt(i - 1);
                }
            }
        }

        public void ResolveCombat(CombatUnit aUnit, CombatUnit dUnit) 
        {
            dUnit.TakeDamage(aUnit.DealDamage());
            //Console.WriteLine("Dom slåss!");
            //Console.WriteLine(dUnit._health);
        }
    }
}
